package admin.controllers.config;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.config.ServiceConfigModel;

import admin.data.config.ServiceConfigData;
import admin.forms.config.ServiceConfigForm;

public class ServiceConfigServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		TreeMap check = new TreeMap();
		
		//Get config name
		String path = ((HttpServletRequest) request).getRequestURI();
		String name = URLDecoder.decode(path.toLowerCase().replaceAll("/admin/config/service/", ""),"UTF-8");
		
		long id = 1;
		ServiceConfigData sData = new ServiceConfigData();
		ServiceConfigModel configs = sData.getConfig(id);
		if (configs == null) {
			configs = new ServiceConfigModel();
		}
		
		request.setAttribute("form", "edit");
		request.setAttribute("check", check);
		request.setAttribute("configs", configs);
		try {
			request.getRequestDispatcher("/admin/pages/config/form_source_url.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		//Get config name
		String path = ((HttpServletRequest) request).getRequestURI();
		String name = URLDecoder.decode(path.toLowerCase().replaceAll("/admin/config/site/", ""),"UTF-8");
		
		long id = 1;
		ServiceConfigData sData = new ServiceConfigData();
		ServiceConfigModel configs = sData.getConfig(id);
		if (configs == null) {
			configs = new ServiceConfigModel();
			configs.setId(1);
		}
		
		//Check valid and get value form
		ServiceConfigForm sForm = new ServiceConfigForm();
		TreeMap forms = sForm.checkValidUrlSource(request, configs);
		configs = (ServiceConfigModel) forms.get("config");
		TreeMap check = (TreeMap) forms.get("checkValid");
		
		if (check.size() == 0) {
			sData.insert(configs);
			request.setAttribute("success", "Update success service config");
		}
		
		request.setAttribute("form", "edit");
		request.setAttribute("check", check);
		request.setAttribute("configs", configs);
		
		try {
			request.getRequestDispatcher("/admin/pages/config/form_source_url.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
